'use strict';
//选择元素
const score0 = document.querySelector('#score--0');
//根据ID获取元素比查询选择器要快
const score1 = document.getElementById('score--1');
const dice = document.querySelector('.dice');
const btnNew = document.querySelector('.btn--new');
const btnRoll = document.querySelector('.btn--roll');
const btnHold= document.querySelector('.btn--hold');
const current0 = document.getElementById('current--0');
const current1 = document.getElementById('current--1');
const player0 = document.querySelector('.player--0');
const player1= document.querySelector('.player--1');
let activePlayer;//player 1，之所以设置为0，方便对应到下标

//切换到另外一个玩家
const changePlayer = function(){
    document.getElementById(`current--${activePlayer}`).textContent = 0;
        currentScore=0;
        activePlayer = activePlayer=== 0 ? 1 : 0;

        //toggle：如果类不存在就创建，如果存在就移除，刚好实现切换后的样式切换
        player0.classList.toggle('player--active');
        player1.classList.toggle('player--active');
}

let scores;
let currentScore ;
let playing ;//判断游戏是否还在继续,如果结束了那么roll和hold按钮都不能按了
//开始条件
const startCondition = function(){
    scores=[0,0];
    currentScore = 0;
    playing = true;//判断游戏是否还在继续,如果结束了那么roll和hold按钮都不能按了
    activePlayer = 0;
    dice.classList.add('hidden');

    current0.textContent =0;
    current1.textContent =0;
    score0.textContent = 0;
    score1.textContent = 0;
    scores[0]=0;
    scores[1]=0;
    
    //即使样式不存在，也不会报错的，存在就删除
     player0.classList.remove('player--winner');
     player1.classList.remove('player--winner');
    
    //如果存在不会再次添加，不存在就添加
    player0.classList.add('player--active');
    player1.classList.remove('player--active');
   
}
startCondition();



//开始掷骰子
btnRoll.addEventListener('click',function(){
    if(playing){
    //1.生成一个随机的骰子
    const number = Math.floor(Math.random()*6+1);
    //2.显示骰子
    dice.classList.remove('hidden');
   //操作标签中的某个属性，如img中的src
    dice.src = `dice-${number}.png`;
    //3.判断骰子是否是1
    if(number!==1){
        //将骰子数增加至current中
        currentScore+=number;
        //不管是player1还是player2，都可以实现当前current的增加
        document.getElementById(`current--${activePlayer}`).textContent = currentScore;
        

    }else{
        //切换到另外一个玩家
        changePlayer();

    }
}
    

});

btnHold.addEventListener('click',function(){
    if(playing){
    //1.添加current分数到总分数中
    scores[activePlayer]+=currentScore;
    document.getElementById(`score--${activePlayer}`).textContent=scores[activePlayer];
    
    //2.检查当前player的总分数是否大于100
    if(scores[activePlayer]>=20){
        playing = false;
        document.querySelector(`.player--${activePlayer}`).classList.add('player--winner');
        document.querySelector(`.player--${activePlayer}`).classList.remove('player--active');
    }
    
    changePlayer();
}
    

});

btnNew.addEventListener('click',function(){
   startCondition();
 
  
  
})